package com.mzj.saas.sdk.pay.callback;

import com.mzj.saas.sdk.util.WechatUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.security.Security;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class WxRefundCallback extends AbstractPayCallback{
	
	private final static Logger logger = LoggerFactory.getLogger(WxRefundCallback.class);

	private String mchApiKey;
	
	private HttpServletRequest request;
	
	private HttpServletResponse response;

	private Map<String, Object> resultMap;
	
	
	public WxRefundCallback(String mchApiKey,HttpServletRequest request,HttpServletResponse response) {
		this.mchApiKey = mchApiKey;
		this.request = request;
		this.response = response;
	}
	
	@Override
	protected String key() {
		// TODO Auto-generated method stub
		return mchApiKey;
	}

	/**
	 * 签名验证
	 * return null错误 ,返回相关数据
	 * 退款通知文档  https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_16&index=10 
	 * refund_status=SUCCESS:退款成功标识
	 * 
	 */
	/*@Override
	public Map<String, String> verifyResult() {
		// TODO Auto-generated method stub
		try {
			String reqParams = WechatUtils.readInputStream(request.getInputStream()); // 读取请求数据流
			Map<String, String> result = WechatUtils.doXMLParse(reqParams); // 将Xml转化为Map
			SortedMap<Object, Object> packageParams = new TreeMap<>();
			Iterator it = result.keySet().iterator();
			while (it.hasNext()) {
				String parameter = (String) it.next();
				String parameterValue = result.get(parameter);
				String v = "";
				if (null != parameterValue) {
					v = parameterValue.trim();
				}
				packageParams.put(parameter, v);
			}
			//加密数据
			String reqInfo = (String) packageParams.get("req_info");
			Security.addProvider(new BouncyCastleProvider());
			Security.addProvider(new BouncyCastleProvider());
			byte[] bt = Base64.decodeBase64(reqInfo);
			String md5key = DigestUtils.md5Hex(mchApiKey).toLowerCase();
			SecretKey secretKey = new SecretKeySpec(md5key.getBytes(), "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			byte[] resultbt = cipher.doFinal(bt);
			String resultStr = new String(resultbt);
			Map<String, String> refund = WechatUtils.doXMLParse(resultStr);
			return refund;
		}catch(Exception e) {
			logger.error("微信支付微信退款 通知-处理异常", e);
		}
		return null;
	}*/

	@Override
	public Map<String, String> verifyResult() {
		try {
			String reqParams = WechatUtils.readInputStream(request.getInputStream()); // 读取请求数据流
			resultMap = WechatUtils.doXMLParse(reqParams); // 将Xml转化为Map
			SortedMap<String, String> packageParams = new TreeMap<>();
			Iterator it = resultMap.keySet().iterator();
			while (it.hasNext()) {
				String parameter = (String) it.next();
				String parameterValue = (String) resultMap.get(parameter);
				String v = "";
				if (null != parameterValue) {
					v = parameterValue.trim();
				}
				packageParams.put(parameter, v);
			}
			return packageParams;
		}catch(Exception e) {
			logger.error("微信支付微信退款 通知-处理异常", e);
		}
		return null;
	}

	@Override
	public Map<String, String> getReqInfo(Map<String,String> packageParams) {
		try {
			//加密数据
			String reqInfo = packageParams.get("req_info");
			Security.addProvider(new BouncyCastleProvider());
			Security.addProvider(new BouncyCastleProvider());
			byte[] bt = Base64.decodeBase64(reqInfo);
			String md5key = DigestUtils.md5Hex(packageParams.get("mch_key")).toLowerCase();
			SecretKey secretKey = new SecretKeySpec(md5key.getBytes(), "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			byte[] resultbt = cipher.doFinal(bt);
			String resultStr = new String(resultbt);
			Map<String, String> refund = WechatUtils.doXMLParse(resultStr);
			return refund;
		}catch (Exception e){
			logger.error("微信支付微信退款 通知-处理异常", e);
		}
		return null;
	}

	/**
	 * 返回成功消息
	 */
	@Override
	public void resultSuccess() throws Exception{
		StringBuffer buffer = new StringBuffer();
		buffer //
				.append("<xml>") //
				.append("<return_code><![CDATA[").append(WechatUtils.SUCCESS).append("]]></return_code>") //
				.append("<return_msg><![CDATA[").append("OK").append("]]></return_msg>") //
				.append("</xml>");
		response.setContentType("text/xml");
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(buffer.toString().getBytes());
		out.flush();
		out.close();
	}

	
	/**
	 * 返回失败消息
	 */
	@Override
	public void resultFail() throws Exception{
		StringBuffer buffer = new StringBuffer();
		buffer //
				.append("<xml>") //
				.append("<return_code><![CDATA[").append(WechatUtils.FAIL).append("]]></return_code>") //
				.append("<return_msg><![CDATA[").append("失败").append("]]></return_msg>") //
				.append("</xml>");
		response.setContentType("text/xml");
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(buffer.toString().getBytes());
		out.flush();
		out.close();
	}

	@Override
	public boolean verifySignature(String... values) {
		//退款业务不需要验证签名
		/*if(resultMap == null) {
			logger.error("verifySignature---> 微信退款结果回调通知-签名验证不通过！resultMap=[{}]", resultMap);
			return false;
		}

		boolean signCheck = WechatUtils.signCheck(resultMap, values[0]);
		if (!signCheck) {
			logger.error("verifySignature---> 微信退款结果回调通知-签名验证不通过！resultMap=[{}]", resultMap);
			return false;
		}*/
		return true;
	}
}
